package com.eastdigit.bpm.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eastdigit.bpm.service.ModelsService;
import com.eastdigit.servlet.RequestAttribute;
import com.eastdigit.servlet.Response;
import com.eastdigit.servlet.ReqBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * Created by Administrator on 2015/9/21.
 */
@Controller
@RequestMapping(value = "/bpm")
public class ModelsController {

    @Autowired
    private ModelsService modelsService;
    @Autowired
    private RepositoryService repositoryService;

    /**
     * 获取模型
     * 
     * @param reqBean
     * @return
     */
    @RequestMapping(value = "/models", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject list(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.response(modelsService.getModels(reqBean));
    }

    /**
     * 创建模型
     * 
     * @param reqBean
     * @return
     */
    @RequestMapping(value = "/models", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject add(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) throws UnsupportedEncodingException {
        return Response.response(modelsService.create(reqBean.getInfo("name"), reqBean.getInfo("key"),
                reqBean.getInfo("category"), reqBean.getInfo("metaInfo")));
    }

    /**
     * 修改模型
     * 
     * @param modelId
     * @param reqBean
     * @return
     */
    @RequestMapping(value = "/models/{modelId}", method = RequestMethod.PUT)
    @ResponseBody
    public JSONObject update(@PathVariable("modelId") String modelId, @RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        modelsService.updateModel(modelId, reqBean.getInfo("name"), reqBean.getInfo("key"),
                reqBean.getInfo("category"), reqBean.getInfo("metaInfo"));
        return Response.responseSuccess();
    }

    /**
     * 删除模型
     * 
     * @param modelId
     * @return
     */
    @RequestMapping(value = "/models/{modelId}", method = RequestMethod.DELETE)
    @ResponseBody
    public JSONObject delete(@PathVariable("modelId") String modelId) {
        modelsService.deleteModel(modelId);
        return Response.responseSuccess();
    }

    /**
     * 
     * 根据Model部署流程
     * 
     * @param modelId
     * @return
     */
    @RequestMapping(value = "/models/{modelId}/deploy", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject queryDepartment(@PathVariable("modelId") String modelId) throws IOException {
        modelsService.deploy(modelId);
        return Response.responseSuccess();
    }

    /**
     * 
     * 根据Model部署流程
     * 
     * @param fileUpload
     * @param request
     * @return
     */
    /*
     * @RequestMapping(value = "/models/deployFile") public void
     * deployFile(final MultipartFile file) { modelsService.deployFile(file); }
     */
    @RequestMapping(value = "/models/import")
    @ResponseBody
    public JSONObject importFile(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) throws Exception{
        modelsService.importByFile(reqBean);
        return Response.responseSuccess();
    }

    /*
     * @RequestMapping(value = "/models/{modelId}/exportDiagramToFile", method =
     * RequestMethod.POST) public InputStream
     * exportDiagramToFile(@PathVariable("modelId") final String
     * modelId,HttpServletResponse response) {
     * 
     * return null; }
     */

    @RequestMapping("/models/{modelId}/export")
    public void download(@PathVariable("modelId") String modelId, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        Model modelData = repositoryService.getModel(modelId);
        try {
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService
                    .getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;

            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);

            String processName = modelData.getName() + ".bpmn20.xml";
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + new String((processName).getBytes("utf-8"), "iso8859-1"));
            ByteArrayInputStream bis = null;
            if (bpmnBytes != null) {
                bis = new ByteArrayInputStream(bpmnBytes);
                OutputStream out = response.getOutputStream();

                for (int b = -1; (b = bis.read()) != -1;) {
                    out.write(b);
                }
                out.close();
                bis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取流程图
     * 
     * @param modelId
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/models/{modelId}/diagram", method = RequestMethod.GET)
    public void diagram(@PathVariable("modelId") String modelId, HttpServletResponse response) throws Exception {
        try {
            ByteArrayInputStream bis = null;
            final byte[] editorSourceExtra = repositoryService.getModelEditorSourceExtra(modelId);
            if (editorSourceExtra != null) {
                try {
                    bis = new ByteArrayInputStream(editorSourceExtra);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            OutputStream out = response.getOutputStream();
            for (int b = -1; (b = bis.read()) != -1;) {
                // 将图写到页面上，用输出流写
                out.write(b);
            }
            out.close();
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
